package com.example.lockfulldemo.service;

import com.example.lockfulldemo.mapper.TicketMapper;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
public class LockService {
    static Lock lock = new ReentrantLock();
    public static volatile Integer ticketNum = 100;
    @Autowired
    private TicketMapper ticketMapper;
    @Autowired
    private RedissonClient redissonClient;
    @Async
    public void asynMethod1(){
        System.out.println(Thread.currentThread().getName() + " 输出");
    }

    @Async
    public void sell(){
        lock.lock();
        try {
            if(ticketNum>0){
                ticketNum--;
                System.out.println(Thread.currentThread().getName()+"卖出门票一张，剩余:" + ticketNum);
            }
        }finally {
            lock.unlock();
        }
    }
    @Async
    public void sellDateBase(){
//        RLock distributeLock = redissonClient.getLock("distributeLock");
//        distributeLock.lock();
//        try {
//            int num = ticketMapper.selectById(1).getNum();
//            if(num>0){
//                num--;
//                ticketMapper.updateById(TicketEntity.builder().id(1).num(num).build());
//                System.out.println(Thread.currentThread().getName()+"卖出门票一张，剩余:" + num);
//            }
//        }finally {
//            distributeLock.unlock();
//        }
    }

}
